/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { BaseElement, element } from '../../base-ui/BaseElement';
import { LitLineChart } from '../../base-ui/chart/lineChart/LitLineChart';
import { LitChartPie } from '../../base-ui/chart/pie/LitChartPie';
import { SpDivChartTemp } from '../sub-template/SpDivChartTemp';
import { LitChartColumns } from '../../base-ui/chart/column/LitChartColumns';
import '../../base-ui/chart/column/LitChartColumns';
import { conversionChartPoints, conversionChartPointsAi } from '../util/SpStatisticsGroupUtil';
import { GroupType } from '../util/SpStatisticsHttpBean';
import { SpStatisticsHttpUtil } from '../util/SpStatisticsHttpUtil';
import * as echarts from 'echarts';
import { SpDivTableTemp } from '../sub-template/SpDivTableTemp';

@element('sp-ai-statistics-panel')
export class SpAiStatisticsPanel extends BaseElement {

    private aiItems: HTMLDivElement | undefined | null;
    private detectTypeTemp: SpDivChartTemp | undefined | null;
    private detectTypeChart: LitChartPie | undefined | null;
    private detectTable: SpDivTableTemp | undefined | null;
    private top10ModelTemp: SpDivChartTemp | undefined | null;
    private top10ModelChart: HTMLDivElement | undefined | null;
    private bottom10ModelTemp: SpDivChartTemp | undefined | null;
    private bottom10ModelChart: HTMLDivElement | undefined | null;
    private xiaolubanTemp: SpDivChartTemp | undefined | null;
    private xiaolubanChart: LitLineChart | undefined | null;
    private aiQATemp: SpDivChartTemp | undefined | null;
    private aiQAChart: LitLineChart | undefined | null;
    private aiDiagnosisTemp: SpDivChartTemp | undefined | null;
    private aiDiagnosisChart: LitLineChart | undefined | null;
    private aiQAFeedBackTemp: SpDivChartTemp | undefined | null;
    private aiQAfeedBackChart: LitChartColumns | undefined | null;
    private detectFeedBackTemp: SpDivChartTemp | undefined | null;
    private detectFeedBackChart: LitChartColumns | undefined | null;
    private detectSuccessTemp: SpDivChartTemp | undefined | null;
    private detectSuccessChart: LitChartColumns | undefined | null;
    private overviewList: any = [];
    // top10所选时间范围内使用过的算法
    private top10ModelMap: Map<string, number> = new Map()
    // 所有已使用过的算法
    private detectModelMap: Map<string, number> = new Map()
    // 所有算法
    private allModelMap: Map<string, number> = new Map()

    initElements(): void {
        this.detectTable = this.shadowRoot?.querySelector<SpDivTableTemp>('.detect-table');
        this.overviewList = [
            {
                title: 'AI问答使用总数量',
                flag: 'qaCount',
                count: 0,
                icon: 'img/faq.png',
                secondCat: "large_model_q&a",
                thirdCat: ""

            },
            {
                title: 'AI问答总点赞数',
                flag: 'qaGoodCount',
                count: 0,
                icon: 'img/qagood.png',
                secondCat: "user_feedback",
                thirdCat: "1"

            },
            {
                title: 'AI问答总点踩数',
                flag: 'qaBadCount',
                count: 0,
                icon: 'img/qabad.png',
                secondCat: "user_feedback",
                thirdCat: "0"

            },
            {
                title: 'AI诊断使用总数量',
                flag: 'detectCount',
                count: 0,
                icon: 'img/detect.png',
                secondCat: "large_model_detect",
                thirdCat: ""
            },
            {
                title: 'AI诊断总点赞数',
                flag: 'detectGoodCount',
                count: 0,
                icon: 'img/detectgood.png',
                secondCat: "feedback_good",
                thirdCat: ""

            },
            {
                title: 'AI诊断总点踩数',
                flag: 'detectBadCount',
                count: 0,
                icon: 'img/detectbad.png',
                secondCat: "feedback_bad",
                thirdCat: ""
            },
            {
                title: '小鲁班使用总数量',
                flag: 'lubanCount',
                count: 0,
                icon: 'img/luban.png',
                secondCat: "smart_luban",
                thirdCat: ""
            }
        ]

        this.aiItems = this.shadowRoot?.querySelector<HTMLDivElement>('.ai-items');
        this.initAiItem();
        this.initDetectTable();
        this.initDetectModelType();
        this.initOtherPages();
    }

    async initAiItem() {
        this.overviewList.forEach((item: any) => {
            let itemDivEl = document.createElement('div');
            itemDivEl.className = 'ai-item';
            let titleDiv = document.createElement('div');
            titleDiv.innerHTML = item.title;
            titleDiv.className = 'ai-item-title';
            let iconDiv = document.createElement('img');
            iconDiv.className = 'ai-item-icon';
            iconDiv.setAttribute('src', item.icon);
            let countDiv = document.createElement('div');
            countDiv.className = 'ai-item-count';
            countDiv.innerHTML = item.count;
            itemDivEl.setAttribute('id', '');
            itemDivEl.appendChild(iconDiv);
            itemDivEl.appendChild(titleDiv);
            itemDivEl.appendChild(countDiv);
            this.aiItems!.appendChild(itemDivEl);
        });
        this.getHeadData();
    }

    initDetectTable() {
        let requestBody = {
            startTime: new Date('2023-01-01T00:00:00Z').getTime(),
            endTime: new Date().getTime(),
            interval: GroupType.YEAR,
            category: "AI_statistic",
            secondCat: "detect_models",
            thirdCat: ""
        }
        let tableData: Array<{}> = [];


        SpStatisticsHttpUtil.getOrdinaryVisitData(
            'generalQuery',
            requestBody,
            (res: any) => {
                if (res.code === 0 && res.data.data) {
                    res.data.data.forEach((item: any) => {
                        item.thirdCat = item.thirdCat.replace(/#/g, '_');
                        if (this.detectModelMap.has(item.thirdCat)) {
                            this.detectModelMap.set(item.thirdCat, this.detectModelMap.get(item.thirdCat) + item.value)
                        } else {
                            this.detectModelMap.set(item.thirdCat, item.value)
                        }
                    });
                }
                requestBody.secondCat = 'all_models';
                SpStatisticsHttpUtil.getOrdinaryVisitData(
                    'generalQuery',
                    requestBody,
                    (resp: any) => {
                        if (resp.code === 0 && resp.data.data) {
                            resp.data.data.forEach((item: any) => {
                                if (this.allModelMap.has(item.thirdCat)) {
                                    this.allModelMap.set(item.thirdCat, this.allModelMap.get(item.thirdCat) + item.value)
                                } else {
                                    this.allModelMap.set(item.thirdCat, item.value)
                                }
                            });
                        }
                        for (const key of this.detectModelMap) {
                            if (!this.allModelMap.has(key[0])) {
                                // @ts-ignore
                                tableData.push({ '算法': key[0], '使用次数': key[1] })
                            }
                        }

                        this.detectTable?.dataSource(tableData);
                    }
                )
            })
    }

    getHeadData() {
        this.overviewList.forEach((item: any, index: number) => {
            let requestBody = {
                startTime: new Date().getTime() - 31536000000 * 2,
                endTime: new Date().getTime(),
                interval: GroupType.YEAR,
                category: "AI_statistic",
                secondCat: item.secondCat,
                thirdCat: item.thirdCat
            }
            // 获取数量
            SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
                if (res.code == 0) {
                    res.data.data.map((v: any) => {
                        item.count += v.value;
                    })
                    let divEL = document.querySelector("body > sp-statistics-application")?.
                        shadowRoot?.querySelector("#ai-root_statistics")?.
                        shadowRoot?.querySelector(`div > div.ai-content > div.ai-items > div:nth-child(${index + 1}) > div.ai-item-count`)
                    divEL!.innerHTML = item.count
                }
            })
        })
    }

    colors = [
        '#3C53C9',
        '#FD7A5F',
        '#FDD761',
        '#7359C2',
        '#42C289',
        '#92E99E',
        '#2E8AE7',
        '#44C1EA',
        '#4Dd621',
        '#ff689b',
        '#fa5c8c',
        '#0acf98',
        '#02a8b4',
        '#39afd2',
        '#726cf5',
        '#6b4eae',
        '#51d59a',
        '#81a6fe',
        '#aa67f6',
        '#cc3fa2',
        '#ffba48',
        '#ff6664',
    ];


    initDetectModelType() {
        this.detectTypeTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#detect_type_template');
        this.detectTypeChart = this.shadowRoot?.querySelector<LitChartPie>('#detectType');
        this.detectTypeTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            this.initDetectModel(startTime, endTime);
        });
    }

    initData() {
        let startStr = SpStatisticsHttpUtil.getPreviousDate(6);
        let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startStr);
        let endTimeStr: string = SpStatisticsHttpUtil.getToday();
        let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
        let dataPickerAttr = {
            datePickerType: 'rangeDate',
            direction: 'bottomLeft',
            dateType: 'date',
            defaultDateValue: `${startStr} ~ ${endTimeStr}`,
        };
        this.detectTypeTemp?.timeData(dataPickerAttr);
        this.top10ModelTemp?.timeData(dataPickerAttr);
        this.bottom10ModelTemp?.timeData(dataPickerAttr);
        this.xiaolubanTemp?.timeData(dataPickerAttr);
        this.aiQATemp?.timeData(dataPickerAttr);
        this.aiDiagnosisTemp?.timeData(dataPickerAttr);
        this.aiQAFeedBackTemp?.timeData(dataPickerAttr);
        this.detectFeedBackTemp?.timeData(dataPickerAttr);
        this.detectSuccessTemp?.timeData(dataPickerAttr);
        this.initDetectModel(startTime, endTime);
        this.initTop10ModelData(startTime, endTime, GroupType.DAY);
        this.initBottom10ModelData(startTime, endTime, GroupType.DAY);
        this.initXiaolubanData(startTime, endTime, GroupType.DAY);
        this.initaiQAData(startTime, endTime, GroupType.DAY);
        this.initAiDiagnosisData(startTime, endTime, GroupType.DAY);
        this.initQAFeedBackData(startTime, endTime, GroupType.DAY);
        this.initDetectFeedBackData(startTime, endTime, GroupType.DAY);
        this.initDetectSuccessData(startTime, endTime, GroupType.DAY);
    }

    initOtherPages() {
        this.xiaolubanTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#xiaoluban_template');
        this.xiaolubanChart = this.shadowRoot?.querySelector<LitLineChart>('#xiaolubanColumn');
        this.xiaolubanTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initXiaolubanData(startTime, endTime, interVal);
        });

        this.top10ModelTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#Top10');
        this.top10ModelChart = this.shadowRoot?.querySelector<HTMLDivElement>('#top10ModelColumn');
        this.top10ModelTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initTop10ModelData(startTime, endTime, interVal);
        });

        this.bottom10ModelTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#Bottom10');
        this.bottom10ModelChart = this.shadowRoot?.querySelector<HTMLDivElement>('#bottom10ModelColumn');
        this.bottom10ModelTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initBottom10ModelData(startTime, endTime, interVal);
        });

        this.aiQATemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#AI-QA');
        this.aiQAChart = this.shadowRoot?.querySelector<LitLineChart>('#aiQAColumn');
        this.aiQATemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initaiQAData(startTime, endTime, interVal);
        });
        this.aiDiagnosisTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#AI-diagnosis');
        this.aiDiagnosisChart = this.shadowRoot?.querySelector<LitLineChart>('#aiDiagnosisColumn');
        this.aiDiagnosisTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initAiDiagnosisData(startTime, endTime, interVal);
        });
        this.aiQAFeedBackTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#QA_feedback_template');
        this.aiQAfeedBackChart = this.shadowRoot?.querySelector<LitChartColumns>('#QAfeedbackChart');
        this.aiQAFeedBackTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initQAFeedBackData(startTime, endTime, interVal);
        });
        this.detectFeedBackTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#detect_feedback_template');
        this.detectFeedBackChart = this.shadowRoot?.querySelector<LitChartColumns>('#detectFeelBackColumn');
        this.detectFeedBackTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initDetectFeedBackData(startTime, endTime, interVal);
        });

        this.detectSuccessTemp = this.shadowRoot?.querySelector<SpDivChartTemp>('#detect_success_template');
        this.detectSuccessChart = this.shadowRoot?.querySelector<LitChartColumns>('#detectSituation');
        this.detectSuccessTemp!.datePickerEl?.addEventListener('date_change', (ev: any) => {
            let detail = ev.detail;
            let startTimeStr = detail.startTime;
            let endTimeStr = detail.endTime;
            let startTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(startTimeStr);
            let endTime: number = SpStatisticsHttpUtil.getCorrectTimeByTimeStr(endTimeStr, true);
            let interVal: number = SpStatisticsHttpUtil.getIntervalCodeByTimeStamp(startTime, endTime);
            this.initDetectSuccessData(startTime, endTime, interVal);
        });
    }



    clearStatisticsPanel() {

    }

    // AI诊断问题类型占比
    initDetectModel(startTs: number, endTs: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: 3,
            category: "AI_statistic",
            secondCat: "detect_models",
            thirdCat: ""
        }
        let data: Array<any> = [];
        let totalCount = 0;
        SpStatisticsHttpUtil.getOrdinaryVisitData(
            'generalQuery',
            requestBody,
            (res: any) => {
                if (res.code === 0) {
                    let modelData: Array<any> = res.data.data;
                    if (modelData) {
                        totalCount = modelData.reduce((pre, cur) => {
                            let isHasSamePlugin = data.some((item: any) => {
                                return item.thirdCat === cur.thirdCat;
                            })
                            if (!isHasSamePlugin) {
                                data.push(cur);
                            } else {
                                data.forEach(item => {
                                    if (item.thirdCat === cur.thirdCat) {
                                        item.value += cur.value;
                                    }
                                })
                            }
                            pre += cur.value;
                            return pre;
                        }, 0)
                        data.sort((a: any, b: any) => {
                            return b.value - a.value;
                        });
                        data = data.slice(0, 20);
                        data?.forEach((model, index) => {
                            model.index = index;
                            model.proportion = Number((model.value / totalCount * 100).toFixed(3)) + '%';
                        });
                        data = data.map((v: any) => {
                            return {
                                name: v.thirdCat,
                                value: v.value
                            }
                        })
                    }
                    let chart = echarts.init(this.detectTypeChart);
                    chart.setOption({
                        title: {
                            text: 'AI诊断模型占比',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)',
                        },
                        legend: {
                            type: 'scroll',
                            orient: 'vertical',
                            right: '20px',
                        },
                        series: [
                            {
                                name: '模型',
                                type: 'pie',
                                center: ['33%', '50%'],
                                radius: '60%',
                                roseType: 'radius',
                                itemStyle:{
                                    borderRadius:8
                                },
                                data,
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                            }
                        ]
                    })
                }
            }
        );
    }

    initTop10ModelData(startTs: number, endTs: number, intervalCode: number) {
        this.top10ModelMap.clear();
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "detect_models",
            thirdCat: ""
        }
        SpStatisticsHttpUtil.getOrdinaryVisitData(
            'generalQuery',
            requestBody,
            (res: any) => {
                if (res.code === 0 && res.data.data) {
                    res.data.data.forEach((item: any) => {
                        if (this.top10ModelMap.has(item.thirdCat)) {
                            this.top10ModelMap.set(item.thirdCat, this.top10ModelMap.get(item.thirdCat) + item.value)
                        } else {
                            this.top10ModelMap.set(item.thirdCat, item.value)
                        }
                    });
                }
                let top10List = Array.from(this.top10ModelMap).sort((a, b) => {
                    return b[1] - a[1]
                }).slice(0, 10);
                let chart = echarts.init(this.top10ModelChart);
                chart.setOption({
                    title: [
                        {
                            left: 'center',
                            text: ' Top10算法统计'
                        },
                    ],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: ''
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    xAxis: [
                        {
                            name: '算法',
                            type: 'category',
                            data: top10List.map(v => {
                                return v[0]
                            }),
                            axisPointer: {
                                type: 'shadow'
                            },
                            axisLabel: { interval: 0, rotate: 45 }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '数量'
                        }
                    ],
                    series: [
                        {
                            type: 'bar',
                            data: top10List.map(v => {
                                return v[1]
                            })
                        }
                    ]
                })
            })
    }

    initBottom10ModelData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: 3,
            category: "AI_statistic",
            secondCat: "all_models",
            thirdCat: ""
        }
        // 所有算法
        let allModelInTimeMap: Map<string, number> = new Map();
        // 使用过的算法
        let detectModelInTimeMap: Map<string, number> = new Map();
        // 比对过后的算法
        let sortModelMap: Map<string, number> = new Map();
        // 获取时间范围内所有诊断出的算法
        let sortDetectArr: any = []
        SpStatisticsHttpUtil.getOrdinaryVisitData(
            'generalQuery',
            requestBody,
            (res: any) => {
                if (res.code === 0 && res.data.data) {
                    res.data.data.forEach((item: any) => {
                        // 整理所有算法，初始化数量为0
                        if (!allModelInTimeMap.has(item.thirdCat)) {
                            allModelInTimeMap.set(item.thirdCat, 0)
                        }
                    });
                };
                requestBody.secondCat = 'detect_models';
                SpStatisticsHttpUtil.getOrdinaryVisitData(
                    'generalQuery',
                    requestBody,
                    (resp: any) => {
                        if (resp.code === 0 && resp.data.data) {
                            resp.data.data.forEach((item: any) => {
                                item.thirdCat = item.thirdCat.replace(/#/g, '_');
                                if (detectModelInTimeMap.has(item.thirdCat)) {
                                    detectModelInTimeMap.set(item.thirdCat, detectModelInTimeMap.get(item.thirdCat) + item.value)
                                } else {
                                    detectModelInTimeMap.set(item.thirdCat, item.value)
                                }
                            });
                            // 补齐所有算法，避免所有算法不全
                            for (let key of detectModelInTimeMap) {
                                if (!allModelInTimeMap.has(key[0])) {
                                    allModelInTimeMap.set(key[0], 0);
                                }
                            }
                            // 遍历所有算法，对比使用过的算法，算出差值
                            for (let key of allModelInTimeMap) {
                                if (detectModelInTimeMap.has(key[0])) {
                                    sortModelMap.set(key[0], detectModelInTimeMap.get(key[0])!)
                                } else {
                                    sortModelMap.set(key[0], 0)
                                }
                            }
                            sortDetectArr = Array.from(sortModelMap).sort((a, b) => {
                                if (a[1] === b[1]) {
                                    return a[0].localeCompare(b[0])
                                }
                                return a[1] - b[1]
                            }).slice(0, 10);
                        }
                        let chart = echarts.init(this.bottom10ModelChart);
                        chart.setOption({
                            title: [
                                {
                                    left: 'center',
                                    text: ' bottom10算法统计'
                                },
                            ],
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'cross',
                                    crossStyle: {
                                        color: ''
                                    }
                                }
                            },
                            toolbox: {
                                feature: {
                                    dataView: { show: true, readOnly: false },
                                    magicType: { show: true, type: ['line', 'bar'] },
                                    restore: { show: true },
                                    saveAsImage: { show: true }
                                }
                            },
                            xAxis: [
                                {
                                    name: '算法',
                                    type: 'category',
                                    data: sortDetectArr.map((v: any) => {
                                        return v[0]
                                    }),
                                    axisPointer: {
                                        type: 'shadow'
                                    },
                                    axisLabel: { interval: 0, rotate: 45 }
                                }
                            ],
                            yAxis: [
                                {
                                    type: 'value',
                                    name: '数量'
                                }
                            ],
                            series: [
                                {
                                    type: 'bar',
                                    data: sortDetectArr.map((v: any) => {
                                        return v[1]
                                    })
                                }
                            ]
                        })
                    })
            })
    }

    initXiaolubanData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "smart_luban",
            thirdCat: '',
        };
        SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
            if (res.code == 0) {
                let chartData = conversionChartPoints(requestBody, {
                    data: res.data.data,
                });
                let dateArr = chartData.data.map((item: any) => {
                    return item.date;
                })
                let dataList = chartData.data.map((item: any) => {
                    return item.value;
                })
                let chart = echarts.init(this.xiaolubanChart);
                chart.setOption({
                    title: [
                        {
                            left: 'center',
                            text: '小鲁班使用数量统计'
                        },
                    ],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: dateArr,
                            axisPointer: {
                                type: 'shadow'
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '数量'
                        }
                    ],
                    series: [
                        {
                            name: '使用量',
                            type: 'line',
                            data: dataList
                        },
                    ]
                })
            }
        });
    }

    initaiQAData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "large_model_q&a",
            thirdCat: ""
        };
        SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
            if (res.code == 0) {
                let chartData = conversionChartPoints(requestBody, {
                    data: res.data.data,
                });
                this.aiQAChart!.dataSource(chartData, {
                    data: 'AI问答使用量',
                });
            }
        });
    }

    initAiDiagnosisData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "large_model_detect",
            thirdCat: ""
        };
        SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
            if (res.code == 0) {
                let chartData = conversionChartPoints(requestBody, {
                    data: res.data.data,
                });
                this.aiDiagnosisChart!.dataSource(chartData, {
                    data: 'AI诊断使用量',
                });
            }
        });
    }

    initQAFeedBackData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "user_feedback",
            thirdCat: ""
        };
        SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
            if (res.code == 0) {
                let good = res.data.data ? res.data.data.filter((v: any) => { return v.thirdCat === '1' }) : [];
                let bad = res.data.data ? res.data.data.filter((v: any) => { return v.thirdCat === '0' }) : [];
                let data1 = conversionChartPointsAi(requestBody, { data: good });
                let data2 = conversionChartPointsAi(requestBody, { data: bad });
                let dateArr = data1.data.map((v: any) => {
                    return v.date;
                })
                let goodArr = data1.data.map((item: any) => {
                    return item.value;
                })
                let badArr = data2.data.map((item: any) => {
                    return item.value;
                })
                let chart = echarts.init(this.aiQAfeedBackChart);
                chart.setOption({
                    title: [
                        {
                            left: 'center',
                            text: 'AI问答反馈统计'
                        },
                    ],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    legend: {
                        data: ['点赞', '点踩'],
                        bottom: '5px'
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: dateArr,
                            axisPointer: {
                                type: 'shadow'
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '数量'
                        }
                    ],
                    series: [
                        {
                            name: '点赞',
                            type: 'bar',
                            data: goodArr
                        },
                        {
                            name: '点踩',
                            type: 'bar',
                            data: badArr
                        }
                    ]
                })
            }
        });
    }

    getColor(index: number) {
        return this.colors[index];
    }

    initDetectFeedBackData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "feedback_good",
            thirdCat: ""
        };
        SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
            if (res.code == 0) {
                requestBody.secondCat = 'feedback_bad';
                SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res1: any) => {
                    if (res1.code === 0) {
                        let goodMergeList: any = [];
                        let badMergeList: any = [];
                        if (res.data.data) {
                            res.data.data.forEach((item: any) => {
                                let isHasSameDate = goodMergeList.some((v: any) => {
                                    if (v.date === item.date) {
                                        v.value += item.value;
                                    }
                                    return v.date === item.date;
                                })
                                if (!isHasSameDate) {
                                    goodMergeList.push(item)
                                }
                            });
                        }
                        if (res1.data.data) {
                            res1.data.data.forEach((item: any) => {
                                let isHasSameDate = badMergeList.some((v: any) => {
                                    if (v.date === item.date) {
                                        v.value += item.value;
                                    }
                                    return v.date === item.date;
                                })
                                if (!isHasSameDate) {
                                    badMergeList.push(item)
                                }
                            });
                        }
                        let data1 = conversionChartPoints(requestBody, { data: goodMergeList });
                        let data2 = conversionChartPoints(requestBody, { data: badMergeList });
                        let dateArr = data1.data.map((item: any) => {
                            return item.date;
                        })
                        let goodArr = data1.data.map((item: any) => {
                            return item.value;
                        })
                        let badArr = data2.data.map((item: any) => {
                            return item.value;
                        })
                        let chart = echarts.init(this.detectFeedBackChart);
                        chart.setOption({
                            title: [
                                {
                                    left: 'center',
                                    text: 'AI诊断反馈统计'
                                },
                            ],
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'cross',
                                    crossStyle: {
                                        color: '#999'
                                    }
                                }
                            },
                            toolbox: {
                                feature: {
                                    dataView: { show: true, readOnly: false },
                                    magicType: { show: true, type: ['line', 'bar'] },
                                    restore: { show: true },
                                    saveAsImage: { show: true }
                                }
                            },
                            legend: {
                                data: ['点赞', '点踩'],
                                bottom: '5px'
                            },
                            xAxis: [
                                {
                                    type: 'category',
                                    data: dateArr,
                                    axisPointer: {
                                        type: 'shadow'
                                    }
                                }
                            ],
                            yAxis: [
                                {
                                    type: 'value',
                                    name: '数量'
                                }
                            ],
                            series: [
                                {
                                    name: '点赞',
                                    type: 'bar',
                                    data: goodArr
                                },
                                {
                                    name: '点踩',
                                    type: 'bar',
                                    data: badArr
                                }
                            ]
                        })
                    }
                })
            }
        });
    }

    initDetectSuccessData(startTs: number, endTs: number, intervalCode: number) {
        let requestBody = {
            startTime: startTs,
            endTime: endTs,
            interval: intervalCode,
            category: "AI_statistic",
            secondCat: "large_model_detect",
            thirdCat: ""
        };
        SpStatisticsHttpUtil.getOrdinaryVisitData('generalQuery', requestBody, (res: any) => {
            if (res.code == 0) {
                let good = res.data.data ? res.data.data.filter((v: any) => { return v.thirdCat === '1' }) : [];
                let bad = res.data.data ? res.data.data.filter((v: any) => { return v.thirdCat === '0' }) : [];
                let data1 = conversionChartPointsAi(requestBody, { data: good });
                let data2 = conversionChartPointsAi(requestBody, { data: bad });
                let myChart = echarts.init(this.detectSuccessChart);
                let dateArr = data1.data.map((v: any) => {
                    return v.date;
                })
                let goodArr = data1.data.map((v: any) => {
                    return v.value;
                })
                let badArr = data2.data.map((v: any) => {
                    return v.value;
                })
                let sumArr: any = [];
                let dataList = data1.data.concat(data2.data)
                for (let i = 0; i < dataList.length; i++) {
                    let isHasSameDate = sumArr.some((v: any) => {
                        return v.date === dataList[i].date
                    });
                    if (isHasSameDate) {
                        sumArr.forEach((item: any) => {
                            if (item.date === dataList[i].date) {
                                item.value += dataList[i].value
                            }
                        })
                    } else {
                        sumArr.push(dataList[i])
                    }
                }
                let sumCounrArr = sumArr.map((v: any) => {
                    return v.value;
                })
                myChart.setOption({
                    title: [
                        {
                            left: 'center',
                            text: 'AI诊断情况统计'
                        },
                    ],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            crossStyle: {
                                color: '#999'
                            }
                        }
                    },
                    toolbox: {
                        feature: {
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    legend: {
                        data: ['诊断出', '未诊断出', '总诊断数'],
                        bottom: '5px'
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: dateArr,
                            axisPointer: {
                                type: 'shadow'
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '数量'
                        }
                    ],
                    series: [
                        {
                            name: '诊断出',
                            type: 'bar',

                            data: goodArr
                        },
                        {
                            name: '未诊断出',
                            type: 'bar',
                            data: badArr
                        },
                        {
                            name: '总诊断数',
                            type: 'line',
                            data: sumCounrArr,
                        }
                    ]
                })
            }
        });
    }

    initHtml(): string {
        return `<style>
            :host{
               width: 100%;
               height: 100%;
            }
    
            .ai-items {
                display: flex;    
                flex-wrap: no-wrap;
                padding: 1% 2%;
                justify-content: space-between;
            }

            .ai-item:hover {
                opacity:0.5;
            }

            .ai-item {
                display: flex;
                flex-wrap:column;
                width: 12%;
                height: 200px;
                border: 0;   
                flex-direction: column;
                align-items: center;
                justify-content: space-around;
                background-color: #fff;
                border-radius: 10px     
            } 
            
            .ai-item-icon{
                height:45%;
                width:45%;
            }

            .ai-item-count {
                font-size:20px;
                font-weight:700;
            }

            .charts {
                padding: 1% 2%;  
                height: 66%;
            }
    
            #detect_type_chart {
                width: 50%;         
                height: 500px; 
            }

            .column{
                height: 300px;
            }
            #detect_model_div{
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .title {
              opacity: 0.8;
              color: #000000;
              text-align: center;
              font: 25px PingFangSC-Regular; 
              overflow: hidden;
            }

            #other_pages_div{
                display: flex;
                flex-wrap:wrap;
                justify-content:space-between;
                align-items:center;
            }

            .echartsPic{
                width:100%;
                height:300px;
            }

            .echartsPiePic {
               width:80%;
               height:500px;
               margin:0 auto;
            }

            
            .detect-tables {
                display: flex; 
                margin:0 0 30px 0;
            }

            .detect-table {
                width: 100%;
            }

            #detectType {
                width:100%;
            }
            
        </style>
        <div class = "ai-panel">
            <div class = "ai-head"></div>
            <div class = "ai-content">
                <div class = "ai-items"></div>
                <div class = "charts">
                    <sp-div-chart-temp id="detect_type_template">
                        <div id = "detectType" class = "echartsPiePic"></div>
                    </sp-div-chart-temp>

                    <div style = "margin-top:30px">
                        <div class="title" >书写错误算法统计</div>
                        <div class="detect-tables">
                            <sp-div-table-temp class="detect-table"></sp-div-table-temp>
                        </div>
                    <div>
                    
                    <div id="other_pages_div">
                        <sp-div-chart-temp id="Top10">
                           <div class="echartsPic" id="top10ModelColumn"></div>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="Bottom10">
                           <div class="echartsPic" id="bottom10ModelColumn"></div>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="AI-QA">
                           <span class="title" >AI问答使用数量统计</span>
                           <lit-line-chart class="column" id="aiQAColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="AI-diagnosis">
                           <span class="title" >ai诊断使用数量统计</span>
                           <lit-line-chart class="column" id="aiDiagnosisColumn"></lit-line-chart>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="QA_feedback_template">
                           <div id = "QAfeedbackChart" class = "echartsPic"></div>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="detect_feedback_template">
                           <div class="echartsPic" id="detectFeelBackColumn"></div>
                        </sp-div-chart-temp>
                         <sp-div-chart-temp id="detect_success_template">
                           <div id = "detectSituation" class = "echartsPic"></div>
                        </sp-div-chart-temp>
                        <sp-div-chart-temp id="xiaoluban_template">
                           <div id = "xiaolubanColumn" class = "echartsPic"></div>
                        </sp-div-chart-temp>
                    </div>
                </div>
            </div>
        </div>
        
    `
    }
}